package com.ming.yygh.order.api;

import com.ming.yygh.common.result.Result;
import com.ming.yygh.order.service.PaymentService;
import com.ming.yygh.order.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author Light
 * @date 2021/12/24 9:28
 */
@Api(tags = "微信支付相关接口")
@RestController
@RequestMapping("api/order/weixin")
public class WeixinController {

    @Resource
    private WeixinService weixinService;

    @Resource
    private PaymentService paymentService;

    @ApiOperation(value = "生成微信支付扫描二维码")
    @GetMapping("/createNative/{orderId}")
    public Result<Map<String, String>> createNative(@PathVariable(value = "orderId") String orderId) {
        Map<String, String> map = weixinService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable(value = "orderId") String orderId) {
        // 调用微信接口实现支付状态查询
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId);
        // 支付状态判断
        if (StringUtils.isEmpty(resultMap)) {
            return Result.fail().message("支付出错");
        }
        if ("SUCCESS".equals(resultMap.get("trade_state"))) { // 支付成功
//        if ("NOTPAY".equals(resultMap.get("trade_state"))) { // 默认支付成功，用来测试
            // 更新订单状态
            String outTradeNo = resultMap.get("out_trade_no");// 订单编码
            paymentService.paySuccess(outTradeNo, resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

}
